<template>
  <el-form ref="form" :model="form" :rules="rulesForm" label-width="100px">
    <el-form-item :label="$t('优惠券类型')" prop="type">
      <el-select v-model="form.type" :disabled="isDisabled" clearable>
        <el-option v-for="item in couponType" :value="item.value" :key="item.value" :label="item.label"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item :label="$t('优惠券名称')" prop="name">
      <el-input v-model="form.name" style="width: 210px" :disabled="isDisabled"/>
    </el-form-item>
    <el-form-item :label="$t('发放数量')" prop="num">
      <el-input v-model="form.num" oninput="value = value.replace(/[^\d]/g, '')" :disabled="visible.type === 'details'"
                style="width: 210px"/>
    </el-form-item>
    <el-form-item :label="$t('面额')" prop="amount">
      <el-radio-group v-model="form.amountType" style="display:block" :disabled="isDisabled">
        <el-radio :label="1">{{ $t('固定面额') }}</el-radio>
        <el-radio :label="2">{{ $t('个性化面额') }}</el-radio>
      </el-radio-group>
      <template v-if="form.amountType === 1">
        <el-input v-model="form.amount" style="width: 210px" oninput="value = value.replace(/[^\d]/g, '')"
                  :disabled="isDisabled" :placeholder="$t('请输入固定面额')"/>
      </template>
      <template v-else>
        <el-input v-model="form.amount" oninput="value = value.replace(/[^\d.]/g, '')" style="width: 210px"
                  :disabled="isDisabled" :placeholder="$t('请输入生成比例')">
          <template slot="append">%</template>
        </el-input>
        <el-alert
            style="margin-top:10px"
            :title="$t('按剩余应还利息/f罚息/金额的百分比生成不同的面额')"
            type="info"
            show-icon
            :closable="false"
        >
        </el-alert>
      </template>
    </el-form-item>
    <el-form-item :label="$t('活动有效期')" prop="activityTimeValue">
      <el-date-picker
          v-model="form.activityTimeValue"
          type="daterange"
          :disabled="visible.type === 'details'"
          value-format="yyyy-MM-dd"
          unlink-panels
          :clearable="false"
          range-separator="~"
          :picker-options="{
            disabledDate(time) {
              return time.getTime() < (Date.now()- (24 * 60 * 60 * 1000))
            }
          }"
          :start-placeholder="$t('开始日期')"
          :end-placeholder="$t('结束日期')">
      </el-date-picker>
    </el-form-item>
    <el-form-item :label="$t('有效天数')" prop="validDay">
      <el-input style="width: 210px" v-model="form.validDay" oninput="value = value.replace(/[^\d]/g, '')"
                :disabled="isDisabled" :placeholder="$t('领取后有效天数')"/>
    </el-form-item>
    <el-form-item :label="$t('获取方式')" prop="getType">
      <el-select v-model="form.getType" :disabled="isDisabled">
        <el-option v-for="item in couponGetType" :value="item.value" :key="item.value"
                   :label="item.label"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item :label="$t('是否推送短信')" prop="sendSms">
      <el-radio-group v-model="form.sendSms" :disabled="isDisabled">
        <el-radio :label="1">{{ $t('是') }}</el-radio>
        <el-radio :label="0">{{ $t('否') }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item :label="$t('发放对象')" prop="sendUser">
      <el-select v-model="form.sendUser" :disabled="isDisabled">
        <el-option v-for="item in sendSmsType" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item :label="$t('发放时间')" prop="smsTime" v-if="form.getType !== 2">
      <template v-for="(item,index) in addNum">
        <div :key="item" style="margin-bottom: 5px">
          <div style="display:inline-block;line-height: 32px">
            D
            <el-input style="width:120px" oninput="value = value.replace(/[^\d]/g, '')"
                      v-model="form.smsTime.startTime[index]" :disabled="isDisabled">
              <template slot="append">天</template>
            </el-input>
          </div>
          <span v-if="form.getType !== 3" style="padding:0 10px">-</span>
          <div v-if="form.getType !== 3" style="display:inline-block;line-height: 32px">
            <el-input style="width:120px" oninput="value = value.replace(/[^\d]/g, '')"
                      v-model="form.smsTime.endTime[index]" :disabled="isDisabled">
              <template slot="append">天</template>
            </el-input>
          </div>
          <el-button :disabled="isDisabled" @click="addNum ++ " style="margin-left: 5px "
                     icon="el-icon-plus"></el-button>
        </div>
      </template>
    </el-form-item>
    <el-form-item :label="$t('发放APP')" prop="sendApp">
      <el-radio-group v-model="form.sendApp" :disabled="isDisabled">
        <el-radio :label="1">{{ $t('全部APP') }}</el-radio>
        <el-radio :label="2">{{ $t('指定APP') }}</el-radio>
        <el-radio :label="3">{{ $t('指定类型') }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item :label="$t('添加APP')" prop="productName" v-if="form.sendApp === 2">
      <el-select v-model="form.productName" :disabled="isDisabled" multiple clearable>
        <el-option v-for="item in productList" :value="item.productName" :key="item.productName"
                   :label="item.appName"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item :label="$t('上架类型')" prop="listType" v-if="form.sendApp === 3">
      <el-checkbox-group v-model="form.listType" :disabled="isDisabled">
        <el-checkbox :label="1">{{ $t('上架') }}</el-checkbox>
        <el-checkbox :label="2">{{ $t('非上架') }}</el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    <el-form-item :label="$t('APP类型')" prop="appType" v-if="form.sendApp === 3">
      <el-checkbox-group v-model="form.appType" :disabled="isDisabled">
        <el-checkbox :label="1">H5</el-checkbox>
        <el-checkbox :label="2">APP</el-checkbox>
      </el-checkbox-group>
    </el-form-item>
    <el-form-item :label="$t('备注')" prop="remark">
      <el-input type="textarea" v-model="form.remark" :rows="4"/>
    </el-form-item>
  </el-form>
</template>

<script>
import {selectProduct} from "@/api/system";
import {addCoupon, updateCoupon} from '@/api/marketing'
import {dateFormat} from "@/utils/tools";

export default {
  name: "addCoupon",
  props: {
    visible: {},
    rows: {}
  },
  data() {
    return {
      form: {
        name: '',
        type: null,
        num: null,
        amount: null,
        amountType: 1,
        activityTimeValue: [],
        validDay: null,
        getType: 1,
        sendUser: null,
        sendApp: 1,
        productName: [],
        sendSms: 0,
        appType: [],
        listType: [],
        remark: '',
        smsTime: {
          startTime: [],
          endTime: [],
        }
      },
      rulesForm: {
        name: [
          {required: true, message: this.$t('请输入')}
        ],
        type: [
          {required: true, message: this.$t('请选择'), trigger: 'change'}
        ],
        num: [
          {
            required: true, validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error(this.$t('不能为空')))
              }
              if (this.visible.type === 'edit' && (parseInt(value) < this.form.num)) {
                return callback(new Error(this.$t('发放数量只能增加不能减少')))
              }
              callback()
            }
          }
        ],
        amount: [
          {
            required: true, validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error(this.$t('不能为空')))
              }
              if (this.form.amountType === 2) {
                if (parseFloat(value) > 100) {
                  return callback(new Error(this.$t('比例最大可输入100%')))
                }
              }
              callback()
            }
          }
        ],
        activityTimeValue: [
          {required: true, message: this.$t('请选择日期'), trigger: 'change',}
        ],
        validDay: [
          {required: true, message: this.$t('请输入'), trigger: 'blur'}
        ],
        getType: [
          {required: true, message: this.$t('请选择'), trigger: 'change'}
        ],
        sendUser: [
          {required: true, message: this.$t('请选择'), trigger: 'change'}
        ],
        productName: [
          {required: true, message: this.$t('请选择'), trigger: 'change', type: 'array'}
        ],
        appType: [
          {required: true, message: this.$t('请选择'), trigger: 'change', type: 'array'}
        ],
        listType: [
          {required: true, message: this.$t('请选择'), trigger: 'change', type: 'array'}
        ],
        smsTime: [
          {
            required: true, validator: (rule, value, callback) => {
              const {startTime, endTime} = value
              if (this.form.getType === 1) {
                if ((startTime.length === 0 || endTime.length === 0) && !startTime.find(item => item) || !endTime.find(item => item)) {
                  return callback(new Error(this.$t('不能为空')))
                }
                for (let key of [...startTime, ...endTime]) {
                  if (parseInt(key) <= 0) {
                    return callback(new Error(this.$t('区间值不能为零')))
                  }
                }
                for (let i = 0; i < startTime.length; i++) {
                  if (startTime[i] > endTime[i]) {
                    return callback(new Error(this.$t('区间值设置错误')))
                  }
                }
              }
              if (this.form.getType === 3) {
                if (startTime.length === 0 && !startTime.find(item => item)) {
                  return callback(new Error(this.$t('不能为空')))
                }
                for (let key of [...startTime]) {
                  if (parseInt(key) <= 0) {
                    return callback(new Error(this.$t('区间值不能为零')))
                  }
                }
              }
              callback()
            }
          }
        ],
      },
      couponType: [
        {label: this.$t("利息券"), value: 1},
        {label: this.$t("还款券"), value: 2},
        {label: this.$t("罚息券"), value: 3}
      ],
      sendSmsType: [
        // {label: this.$t("游客"), value: 1},
        // {label: this.$t("注册未申请"), value: 2},
        // {label: this.$t("待还款"), value: 3},
        // {label: this.$t("结清未复借"), value: 5},
        {label: this.$t("逾期"), value: 4},
      ],
      addNum: 1,
      productList: [],
      couponGetType: [
        {label: this.$t("用户主动领取"), value: 1},
        {label: this.$t("手动定向发放"), value: 2},
        {label: this.$t("系统自动触发发放"), value: 3}
      ],
    }
  },
  watch: {
    rows: {
      handler(value) {
        if (value && Object.keys(value).length) {
          this.form = {
            ...this.form,
            name: value.name,
            type: value.type,
            num: value.num,
            amount: value.amount,
            amountType: value.amountType,
            activityTimeValue: [value.activityStartTime, value.activityEndTime],
            validDay: value.validDay,
            getType: value.getType,
            sendUser: value.sendUser,
            sendApp: value.sendApp,
            productName: value.productName ? value.productName.split(',') : [],
            sendSms: value.sendSms,
            appType: value.appType ? value.appType.split(',').map(item => parseInt(item)) : [],
            listType: value.listType ? value.listType.split(',').map(item => parseInt(item)) : [],
            remark: value.remark,
          }
          if (value.getType === 1) {
            this.form.smsTime['startTime'] = [value.sendStartTime].filter(item => item)
            this.form.smsTime['endTime'] = [value.sendEndTime].filter(item => item)
          } else if (value.getType === 3) {
            this.form.smsTime['startTime'] = [value.sendStartTime].filter(item => item)
          }
        }
      },
      immediate: true
    }
  },
  computed: {
    isDisabled() {
      const type = this.visible.type
      return type === 'edit' || type === 'details'
    }
  },
  mounted() {
    selectProduct().then(res => {
      this.productList = res.data
    })
  },
  methods: {
    submitForm() {
      return new Promise((resolve) => {
        this.$refs.form.validate(async v => {
          if (v) {
            const [activityStartTime, activityEndTime] = this.form.activityTimeValue
            const params = {
              upType: 0,
              type: this.form.type,
              name: this.form.name,
              num: this.form.num,
              amount: this.form.amount,
              amountType: this.form.amountType,
              validDay: this.form.validDay,
              getType: this.form.getType,
              sendUser: this.form.sendUser,
              sendApp: this.form.sendApp,
              sendSms: this.form.sendSms,
              remark: this.form.remark,
              activityStartTime,
              activityEndTime,
              id: this.rows.id
            }
            if (this.form.sendApp === 3) {
              params['appType'] = this.form.appType.join(',')
              params['listType'] = this.form.listType.join(',')
            } else if (this.form.sendApp === 2) {
              params['productName'] = this.form.productName.join(',')
            }
            if (this.form.getType === 1) {
              params['startTime'] = this.form.smsTime.startTime.map(item => parseInt(item))
              params['endTime'] = this.form.smsTime.endTime.map(item => parseInt(item))
            } else if (this.form.getType === 3) {
              params['startTime'] = this.form.smsTime.startTime.map(item => parseInt(item))
              params['endTime'] = this.form.smsTime.startTime.map(item => parseInt(item))
            }
            const isAdd = this.visible.type === 'add'
            if (!isAdd) {
              params['activityStatus'] = 1
            }
            const api = (params) => isAdd ? addCoupon(params) : updateCoupon(params)
            const res = await api(params)
            if (res.code === 1) {
              this.$message.success(isAdd ? '添加成功' : '编辑成功')
              resolve(res)
            }
          }
        })
      })
    },
    clearForm() {
      this.addNum = 1
      this.form = {
        name: '',
        type: null,
        num: null,
        amount: null,
        amountType: 1,
        activityTimeValue: [],
        validDay: null,
        getType: 1,
        sendUser: null,
        sendApp: 1,
        productName: [],
        sendSms: 0,
        appType: [],
        listType: [],
        remark: '',
        smsTime: {
          startTime: [],
          endTime: [],
        }
      }
      this.$refs.form.clearValidate()
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style scoped>

</style>
